//
//  VKVoucherChildController.m
//  V-Learn
//
//  Created by liubo on 2019/1/10.
//  Copyright © 2019 yxk. All rights reserved.
//

#import "VKMeOrderChildController.h"
#import "VKMeOrderCell.h"
#import "VKMeWeiOrderCell.h"
#import "LBPayVC.h"
@interface VKMeOrderChildController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSIndexPath *editingIndexPath;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger pageNums;
@end

@implementation VKMeOrderChildController
-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}
- (instancetype)initWithOrderId:(NSString *)orderId
{
    self = [super init];
    if (self) {
        self.orderId = orderId;
    }
    return self;
}
-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen cz_screenWidth], [UIScreen cz_screenHeight] - LBNAVBAR_HEIGHT - 40) style:UITableViewStylePlain];
        _tableView.tableFooterView = [UIView new];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.view addSubview:_tableView];
        _tableView.backgroundColor = [UIColor cz_colorWithRed:244 green:244 blue:244];
    }
    return _tableView;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self setupLeftRefresh];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = @[];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self tableView];
    
}
//刷新
- (void)setupLeftRefresh
{   //下拉
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(setupLoadData)];
    //上拉
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(setupLoadMoreData)];
    
    [self.tableView.mj_header beginRefreshing];
}
- (void)setupLoadData{
    _page = 1;
    _pageNums = 10;
    [self setupLoadFirstData];
}
/**
 加载更多数据
 */
- (void)setupLoadMoreData{
    
    ++(_page);
    _pageNums = 10;
    [self setupLoadFirstData];
}//决定footer的状态
- (void)checkFooterState{
    
    [self.tableView.mj_footer endRefreshingWithNoMoreData];
}

- (void)setupLoadFirstData{
    VKWeakSelf(self)
    NSMutableDictionary *pagramsD = @{@"token":[UserModel getUserModel].token,@"orderStatus":[self.orderId integerValue] == 1?@2:@1,@"page":[NSString stringWithFormat:@"%ld",(long)_page],@"num":[NSString stringWithFormat:@"%ld",(long)_pageNums]}.mutableCopy;
    [WYHXNetWorkService netWorkSerViceRequestWithGetUrl:WKMeOrder withPostParams:pagramsD withBlock:^(NSDictionary *result, NSError *error) {

        if ([result[@"code"]integerValue] == 200) {
            if (weakself.page == 1) {
                [self.dataArray removeAllObjects];
            }

//            for (NSDictionary *dic in result[@"data"]) {
//                VKMeOrderModel *model = [VKMeOrderModel mj_objectWithKeyValues:dic];
//                [self.dataArray addObject:model];
//            }
            NSArray *arr = [VKMeOrderModel mj_objectArrayWithKeyValuesArray:result[@"data"]];
            [self.dataArray addObjectsFromArray:arr];
//            _moneyLabel.text = [NSString stringWithFormat:@"%@",result[@"Data"][@"count"]];
            if ([result[@"data"] count] < 10) {
                //不能加载更多数据
                [self checkFooterState];
                [MBProgressHUD showSuccess:@"已加载全部数据" toView:self.view];
            }else{
                [self.tableView.mj_footer endRefreshing];
            }
        }else{
//            [MBProgressHUD showSuccess:result[@"msg"] toView:self.view];
        }
        [weakself.tableView reloadData];

        [self.tableView.mj_header endRefreshing];
    }];
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 180;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return UITableViewCellEditingStyleDelete;
    
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        [tableView reloadData];
    }
}
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    VKWeakSelf(self)

    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//        NSLog(@"点击了删除:%ld",(long)indexPath.row);
        int index = [self.orderId integerValue] == 1? 2: 1;
        VKMeOrderModel *model = self.dataArray[indexPath.row];
        // 已支付
        if (index == 2) {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.labelText = @"正在加载...";
            [hud show:YES];
            NSMutableDictionary *pagramsD = @{@"token":[UserModel getUserModel].token,@"orderId":model.orderId}.mutableCopy;
            [WYHXNetWorkService netWorkSerViceRequestWithPostUrl:WKMeDeleteOrder withPostParams:pagramsD withBlock:^(NSDictionary *result, NSError *error) {
                hud.hidden = YES;
//                NSLog(@"result:%@",result);
                if ([result[@"code"]integerValue] == 200) {
                    [self.dataArray removeObject:model];
                    [MBProgressHUD showSuccess:@"删除成功" toView:self.view];
                }else{
                    [MBProgressHUD showSuccess:@"删除失败" toView:self.view];
                }
                [weakself.tableView reloadData];
            }];
        }else if(index == 1){ // 待支付
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.labelText = @"正在加载...";
            [hud show:YES];
            NSMutableDictionary *pagramsD = @{@"token":[UserModel getUserModel].token,@"orderId":@([model.orderId integerValue])}.mutableCopy;
            [WYHXNetWorkService netWorkSerViceRequestWithPostUrl:WKMeDeleteOrder withPostParams:pagramsD withBlock:^(NSDictionary *result, NSError *error) {
                hud.hidden = YES;
//                NSLog(@"result:%@",result);
                if ([result[@"code"]integerValue] == 200) {
                    [self.dataArray removeObject:model];
                    [MBProgressHUD showSuccess:@"删除成功" toView:self.view];
                }else{
                    [MBProgressHUD showSuccess:@"删除失败" toView:self.view];
                }
                [weakself.tableView reloadData];
            }];
        }
        
        
        [self setEditing:NO animated:YES];
    }];
    deleteAction.backgroundColor = [UIColor cz_colorWithRed:244 green:244 blue:244];
    return @[deleteAction];
}
-(void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath{
    self.editingIndexPath = indexPath;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self setupSlideBtn];
    });
}
-(void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath{
    self.editingIndexPath = nil;
}
- (void)setupSlideBtn{
    if (@available(iOS 11.0, *)){
        
        // iOS 11层级 (Xcode 9编译): UITableView -> UISwipeActionPullView
        for (UIView *subview in self.tableView.subviews){
//            NSLog(@"%@-----%zd",subview,subview.subviews.count);
            if ([subview isKindOfClass:NSClassFromString(@"UISwipeActionPullView")] && [subview.subviews count] >= 1){
                // 和iOS 10的按钮顺序相反
                UIButton *deleteButton = subview.subviews[0];
                [self configDeleteButton:deleteButton];
            }
        }
    }else{
        // iOS 8-10层级 (Xcode 8编译): UITableView -> UITableViewCell -> UITableViewCellDeleteConfirmationView
        VKMeOrderCell *tableCell = [self.tableView cellForRowAtIndexPath:self.editingIndexPath];
        for (UIView *subview in tableCell.subviews){
            NSLog(@"subview%@-----%zd",subview,subview.subviews.count);
            
            if ([subview isKindOfClass:NSClassFromString(@"UITableViewCellDeleteConfirmationView")] && [subview.subviews count] >= 1){
                UIButton *deleteButton = subview.subviews[0];
                [self configDeleteButton:deleteButton];
            }
        }
    }
    
}
- (void)configDeleteButton:(UIButton*)deleteButton{
    if (deleteButton) {
        [deleteButton setImage:[UIImage imageNamed:@"vkdelete"] forState:UIControlStateNormal];
        [deleteButton setBackgroundColor:[UIColor cz_colorWithRed:244 green:244 blue:244]];
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    int index = [self.orderId integerValue] == 1? 2: 1;
    // 已支付
    if (index == 2) {
        VKMeWeiOrderCell *cell = [VKMeWeiOrderCell cellWithTableView:tableView];
        cell.model = self.dataArray[indexPath.row];
        return cell;
    }else if(index == 1){ // 待支付
        VKMeOrderCell *cell = [VKMeOrderCell cellWithTableView:tableView];
        cell.model = self.dataArray[indexPath.row];
        cell.payBtn.tag = indexPath.row + 100;
        [cell.payBtn addTarget:self action:@selector(payBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
        
    }
    return nil;
}
- (void)payBtnClick:(UIButton *)sender{
    VKMeOrderModel *model = self.dataArray[sender.tag - 100];

    LBPayVC *pay = [LBPayVC new];
    pay.type = model.courseType;//1 课时 2 课程包
    pay.name = model.courseName;
    pay.courserId = model.courseId;
    pay.price = model.coursePrice;

    [self.navigationController pushViewController:pay animated:YES];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


@end
